package org.apache.lucene.index;

import java.io.IOException;
import java.util.Arrays;

import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMOutputStream;

public class TagBlocksData {
  private int[] docs;
  private RAMOutputStream output;
  private TagBlockWriter[] tagBlockWriters;
  private int termNum;
  private int[] docFreqs;
  private long[] positions;

  public TagBlocksData(int termNum, int[] docs, int skipInterval, int maxSkipLevels, int[] starts, int[] numDocsPerBlock) throws IOException {
    this.termNum = termNum;
    this.docs = docs;
    int pos = 0;
    tagBlockWriters = new TagBlockWriter[numDocsPerBlock.length];
    docFreqs = new int[numDocsPerBlock.length];
    positions = new long[numDocsPerBlock.length];
    for (int doc : docs) {
      while (pos < numDocsPerBlock.length) {
        if (starts[pos] <= doc && doc < starts[pos + 1]) {
          if (tagBlockWriters[pos] == null)
            tagBlockWriters[pos] = new TagBlockWriter(skipInterval, maxSkipLevels, numDocsPerBlock[pos]);
          tagBlockWriters[pos].add(doc - starts[pos]); // doc minus base
          break;
        } else {
          pos++;
        }
      }
    }
    Arrays.fill(docFreqs, 0);
    Arrays.fill(positions, 0);
    for (int x=0; x < tagBlockWriters.length; x++) {
      if (tagBlockWriters[x] != null) {
        docFreqs[x] = tagBlockWriters[x].getDocFreq();
        positions[x] = output.getFilePointer();
        tagBlockWriters[x].write(output);
      }
    }
  }
  
  public long[] getPositions() {
    return positions;
  }
  
  public int[] getDocFreqs() {
    return docFreqs;
  }
  
  public void write(IndexOutput io) throws IOException {
    output.writeTo(io);
  }

  public int length() {
    return (int)output.length();
  }
}
